import time  # 导入 time 库
import os  # 导入 os 库

from package.Utils.log import logger,mylog  # 导入 logger 对象(python代码)
from package.Utils.Screen import screen   # 导入 screen 对象(python代码)


# QQ轰炸机
class MyTask1:
    def __init__(self):
        pass
    def run(self):
        from Utils.MainWindow import myTask1Win # 导入 myTask1Win 对象(python代码)
        while myTask1Win.timeout > 0:  # 循环执行任务
            if mylog.log_enabled is True:
                logger.info(f"倒计时：{myTask1Win.timeout}s 后开始执行")
            time.sleep(1)  # 等待1s
            myTask1Win.timeout -= 1  # 计数器减1
        if mylog.log_enabled is True:
            logger.info("Task1 is running...")
        screen.Copy(myTask1Win.text)    # 复制
        screen.get_Mouse_Position()  # 获取鼠标位置
        for i in range(myTask1Win.count):
            screen.Control_Mouse_Click(screen.Mouse_Position_x,screen.Mouse_Position_y)  # 点击鼠标
            screen.Paste()  # 粘贴
            time.sleep(0.1)  # 等待0.1s
            screen.Control_Keyboard_Input('\n') # 输入回车
            time.sleep(myTask1Win.interval)  # 等待间隔时间
            if mylog.log_enabled is True:
                logger.info(f"Task1 is running...{i+1}/{myTask1Win.count}")
        if mylog.log_enabled is True:
            logger.info("Task1 is finished.")
        myTask1Win.interval = 0  # 重置间隔时间
        myTask1Win.count = 0  # 重置循环次数
        myTask1Win.text = ""  # 重置发送内容

# QQ轰炸机
class MyTask2:
    def __init__(self):
        pass
    def run(self):
        from Utils.MainWindow import myTask2Win # 导入 myTask2Win 对象(python代码)
        if mylog.log_enabled is True:
            logger.info("Task2 is running...")

        self.replace_text_in_files(myTask2Win.dir_path,myTask2Win.OldWord,myTask2Win.NewWord)  # 替换文本

        if mylog.log_enabled is True:
            logger.info("Task2 is finished.")

    def replace_text_in_files(self, directory, old_text, new_text):
        for filename in os.listdir(directory):
            if filename.endswith((".txt",".py",".c",".h")):
                file_path = os.path.join(directory, filename)
                with open(file_path, 'r', encoding='utf-8') as file:
                    file_data = file.read()
                file_data = file_data.replace(old_text, new_text)
                with open(file_path, 'w', encoding='utf-8') as file:
                    file.write(file_data)
                if mylog.log_enabled is True:
                    logger.info(f"'{filename}' 的内容已替换")
